﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BacteriaSimulation.Simulation
{
    public class Vector2D
    {
        public static Random random = new Random();

        public Double XComponent { get; set; }
        public Double YComponent { get; set; }

        protected Vector2D()
        {
        }

        public Vector2D(Double xComponent, Double yComponent)
        {
            this.XComponent = xComponent;
            this.YComponent = yComponent;
        }

        public static Vector2D GetRandomVector2D(Double maxSpeedComponent)
        {
            int randomSign = 1;
            randomSign = random.NextDouble() < 0.5 ? 1 : -1;
            Double xComp = random.NextDouble() * maxSpeedComponent * randomSign;
            randomSign = random.NextDouble() < 0.5 ? 1 : -1;
            Double yComp = random.NextDouble() * maxSpeedComponent * randomSign;
            Vector2D vector = new Vector2D(xComp, yComp);

            return vector;
        }

        public Double GetSquareMagnitude()
        {
            double squareMagnitude = XComponent * XComponent + YComponent * YComponent;
            return squareMagnitude;
        }

        public Double GetMagnitude()
        {
            double magnitude = SimulationPoint.Distance(new SimulationPoint(0, 0), new SimulationPoint(this.XComponent, this.YComponent));
            return magnitude;
        }

        public static Vector2D GetRandomVector2D(SimulationEnvironment env)
        {
            return GetRandomVector2D(SimulationEnvironment.MAX_SPEED_COMPONENT);
        }

        public Vector2D Clone()
        {
            Vector2D clone = new Vector2D(this.XComponent, this.YComponent);
            return clone;
        }

        /// <summary>
        /// Computes a vector with the same direction and orientation as the given one but with magnidute equals to the <code>magnitude</code> parameter
        /// </summary>
        /// <param name="vector">the original vector</param>
        /// <param name="magnitude">the desired magnitude to which <code>vector</code> is to be scaled</param>
        /// <returns></returns>
        public static Vector2D normalizeToMagnitude(Vector2D vector, double magnitude)
        {
            double xNormalized = 0.0;
            double yNormalized = 0.0;
            double vectorMagnitude = vector.GetMagnitude();
            if (vectorMagnitude > 0)
            {
                xNormalized = (magnitude * vector.XComponent) / vectorMagnitude;
                yNormalized = (magnitude * vector.YComponent) / vectorMagnitude;
            }
            return new Vector2D(xNormalized, yNormalized);
        }
    }
}
